package com.wdf.dota;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.wdf.bean.Comment;
import com.wdf.bean.CommentReply;
import com.wdf.bean.Page;
import com.wdf.helper.TimeUtils;
import com.wdf.rest.service.DotaDiscussionRestClient;

public class HeroDiscussionActivity extends Activity {

	ListView commentView;
	Button prevPageBtn;
	Button nextPageBtn;
	
	
	
	TextView historyPageTv;
	LinearLayout pagnitationLinearLayout;

	List<Comment> commentList;
	Page<Comment> page;
	String loginName;
	String contactName;
	DotaDiscussionRestService discussionService;

	private BaseAdapter adapter;
	private static final int STATUS_CHANGE = 0;
	
	public Handler mHandler;

	
	String topic;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.hero_discuss);
		commentView = (ListView) findViewById(android.R.id.list);

		prevPageBtn = (Button) findViewById(R.id.chat_prev_page);
		nextPageBtn = (Button) findViewById(R.id.chat_next_page);

		
		historyPageTv = (TextView) findViewById(R.id.history_page);
		historyPageTv = (TextView) findViewById(R.id.history_page);
		
		Bundle bundle = this.getIntent().getExtras();
		String heroname =	bundle.getString("heroname");
        topic = heroname;
        
        pagnitationLinearLayout =  (LinearLayout ) findViewById(R.id.pagnitation_linearLayout);

		discussionService = new DotaDiscussionRestService(topic);
		page = new Page<Comment>();
	
		 
		commentList = page.getResult();
		updateTextView();
		prevPageBtn.setOnClickListener(prevPageButtonListener);
		nextPageBtn.setOnClickListener(nextPageButtonListener);
		
	

		adapter = new DiscussionListAdapter(HeroDiscussionActivity.this);
		commentView.setAdapter(adapter);

		mHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case STATUS_CHANGE:
					// 处理UI更新等操作
					updateUI();
				}
			};
		};

		
		discussionService.getDiscussions();
		

		
	}
	
	private boolean validateComment(String id){
		SharedPreferences sharedPreferences = getSharedPreferences("wonderful",
				Context.MODE_PRIVATE);
	String key = topic +"-" + id;
	 int	times = sharedPreferences.getInt(key, 0);
	 if(times == 0){
		 return true;
	 }
	  Toast.makeText(this, "请勿重复评论!", 2).show();
		 return false;
	}

	private void updateUI() {
		if( page.getResult().size() <= page.getPageSize()){
			pagnitationLinearLayout.setVisibility(View.GONE);
		}else{
			pagnitationLinearLayout.setVisibility(View.VISIBLE);
		}
		// 详细的更新
		adapter.notifyDataSetChanged();// 更新ListView
		updateTextView();
	}

	/**
	 * 更新页码
	 */
	private void updateTextView() {
		if (commentList.size() == 0) {
			historyPageTv.setText(0 + "/" + 0);
		} else {
			historyPageTv.setText(page.getPageNo() + 1 + "/"
					+ page.getTotalPages());
		}
		if(commentView!=null && commentView.getChildCount() >0){
			commentView.setSelection(0);
		}
	}

	public class DiscussionListAdapter extends BaseAdapter {

		private class RecentViewHolder {
			TextView commentIdView;
			TextView usernameView;
			TextView sender_context;
			TextView replyView;
			TextView rTime;
			Button supporter;
			Button protester;
			Button reply;
		}

		Context context;
		LayoutInflater mInflater;

		public DiscussionListAdapter(Context context) {
			this.context = context;
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {

			return page.getDisplayCount();
		}

		@Override
		public Object getItem(int position) {
			return page.getItem(position);
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			RecentViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.hero_discuss_item,
						null);
				holder = new RecentViewHolder();
				holder.commentIdView = (TextView) convertView.findViewById(R.id.comment_id);
				holder.usernameView = (TextView) convertView.findViewById(R.id.username);
				holder.supporter = (Button)convertView.findViewById(R.id.supporter);
				holder.protester = (Button)convertView.findViewById(R.id.protester);
				holder.reply = (Button)convertView.findViewById(R.id.comment_reply);
				holder.sender_context = (TextView) convertView.findViewById(R.id.message_view_sender_content);
				holder.rTime = (TextView) convertView.findViewById(R.id.message_view_timestamp);
				holder.replyView= (TextView) convertView.findViewById(R.id.message_view_sender_reply);
				convertView.setTag(holder);
			} else {
				holder = (RecentViewHolder) convertView.getTag();
			}
			Comment comment = (Comment)getItem(position);;
			final String commentId =""+ comment.getId();
			if (comment != null) {
				holder.commentIdView.setText(""+comment.getId());
				holder.sender_context.setText(comment.getContent());
				holder.rTime.setText(comment.getCreatetime());
				holder.usernameView.setText(comment.getNickname());
				holder.supporter.setText("支持("+comment.getSupporter()+")");
				holder.protester.setText("反对("+comment.getProtester()+")");
				StringBuffer sb = new StringBuffer();
				for(CommentReply reply : comment.getReplys()){
					sb.append(reply.getUsername() +" 回复:  "+reply.getContent()+"\n");
				}
				holder.replyView.setText(sb.toString());
				holder.supporter.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if( validateComment(commentId)){
						  discussionService.supportDiscussion(commentId);
						}
					}
				});
				holder.protester.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if( validateComment(commentId)){
						discussionService.protestDiscussion(commentId);
						}
					}
				});
				holder.reply.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						 SharedPreferences sharedPreferences = getSharedPreferences("wonderful",
									Context.MODE_PRIVATE);
						   String accountid= sharedPreferences.getString("accountid", "0");
						   String username = sharedPreferences.getString("username", "");
						   
			             if("0".equals(accountid) || username ==null || username.length() <=0){
			            	 Intent intent = new Intent(HeroDiscussionActivity.this,
			            			 LoginActivity.class);
			            	  startActivityForResult(intent, 4);
			             }else{
			            		Intent intent = new Intent(HeroDiscussionActivity.this,
										CommentReplyActivity.class);
								Bundle bundle = new Bundle();
								bundle.putString("commentId", commentId);
			        			intent.putExtras(bundle);
			        			startActivityForResult(intent, 4);
			             }
					

					}
				});
			}
			return convertView;
		}
	}

	/**
	 * 上一页按钮的监听事件
	 */
	OnClickListener prevPageButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (page.isHasPre()) {
				page.setPageNo(page.getPageNo() - 1);
				updateUI();
			}

		}
	};

	/**
	 * 下一页按钮的监听事件
	 */
	OnClickListener nextPageButtonListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (page.isHasNext()) {
				page.setPageNo(page.getPageNo() + 1);
				updateUI();
			}

		}
	};

	public void onResume() {
		super.onResume();
		 discussionService.getDiscussions();
	}

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	            super.onActivityResult(requestCode, resultCode, data);
	            discussionService.getDiscussions();
	}
	
	class DotaDiscussionRestService {
        private String topic ;
        
        public DotaDiscussionRestService(String topic){
        	this.topic = topic;
        }
		
		 public  void  getDiscussions(){
 			final RequestParams params = new RequestParams();
			        params.put("topic", topic);
			 DotaDiscussionRestClient.get("/dota/discussions.json", params, new JsonHttpResponseHandler() {
				 
		            @Override
		            public void onSuccess(JSONArray elements) {
		                try {
		                	if(elements!=null){
		                	 List<Comment> comments = new ArrayList<Comment>();
		                	 for(int i=0;i < elements.length();i++){
		                		 JSONObject object = elements.getJSONObject(i);
		                		 JSONArray replys =  object.getJSONArray("commentReply");
		                		
		                		
		                		 Comment comment = new Comment();
		                		 for(int j=0;j<replys.length();j++){
		                			 JSONObject reply = replys.getJSONObject(j);
		                			 String desc = reply.getString("content");
		                			 JSONObject account = reply.getJSONObject("account");
		                			 String username = account.getString("username");
		                			 CommentReply commentReply = new CommentReply();
		                			 commentReply.setContent(desc);
		                			 commentReply.setUsername(username);
		                			 comment.getReplys().add(commentReply);
		                		 }
		                		 
		                		 comment.setContent(object.getString("content"));
		                		 comment.setCreatetime(TimeUtils.timePast(object.getString("createtime")));
		                		 
		                		 comment.setId(object.getInt("id"));
		                		 comment.setNickname(object.getString("nickname"));
		                		 comment.setProtester(object.getInt("protester"));
		                		 comment.setSupporter(object.getInt("supporter"));
		                		 comment.setTopic(object.getString("topic"));
		                		 comment.setUserid(object.getInt("userid"));
		                		 comments.add(comment);
		                	 }
		                	 commentList = comments;
		                	 page.setResult(comments);
		                	 page.setTotalCount(comments.size());
		                	 updateUI();
		                	}

		                } catch (Exception e) {
		                    e.printStackTrace();
		                }
		                
		            }
		        });

		 }
		 
		 
		 public  void  supportDiscussion(final String id){
	 			final RequestParams params = new RequestParams();
			//	 params.put("commentId", id);
				 DotaDiscussionRestClient.put("/dota/discussions/support.json?commentId="+id, params, new JsonHttpResponseHandler() {
					 
			            @Override
			            public void onSuccess(JSONObject object) {
			            	SharedPreferences sharedPreferences = getSharedPreferences("wonderful",
			        				Context.MODE_PRIVATE);
			            	Editor editor = sharedPreferences.edit();
			            	String key = topic +"-" + id;
			            	editor.putInt(key, 1);
			            	editor.commit();
			            	discussionService.getDiscussions();
			            	
			            }
			        });

			 }	
		 
		 public  void  protestDiscussion(final String id){
	 			final RequestParams params = new RequestParams();
	 		//	params.put("commentId", id);
				 DotaDiscussionRestClient.put("/dota/discussions/protest.json?commentId="+id, params, new JsonHttpResponseHandler() {	 
			            @Override
			            public void onSuccess(JSONObject object) {
			            	SharedPreferences sharedPreferences = getSharedPreferences("wonderful",
			        				Context.MODE_PRIVATE);
			            	Editor editor = sharedPreferences.edit();
			            	String key = topic +"-" + id;
			            	editor.putInt(key, 1);
			            	editor.commit();
			            	discussionService.getDiscussions();
			            }
			        });

			 }	
	}

}